package com.hzncc.flowable_diboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.binding.QueryBuilder;
import com.diboot.core.service.impl.BaseServiceImpl;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.vo.Pagination;
import com.hzncc.flowable_diboot.dto.OppoFlowTemplateItemDTO;
import com.hzncc.flowable_diboot.entity.OppoFlowOrder;
import com.hzncc.flowable_diboot.entity.OppoFlowOrderItem;
import com.hzncc.flowable_diboot.entity.OppoFlowTemplate;
import com.hzncc.flowable_diboot.entity.OppoFlowTemplateItem;
import com.hzncc.flowable_diboot.mapper.OppoFlowOrderMapper;
import com.hzncc.flowable_diboot.service.*;
import com.hzncc.flowable_diboot.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;


/**
 * 商机流程单 相关Service实现类
 *
 * @author MyName
 * @version 1.0
 * @date 2024-06-11
 * Copyright © MyCorp
 */
@Slf4j
@Service
public class OppoFlowOrderServiceImpl extends BaseServiceImpl<OppoFlowOrderMapper, OppoFlowOrder> implements OppoFlowOrderService {

    private final OppoFlowOrderItemService oppoFlowOrderItemService;
    private final OppoFlowOrderDetailService oppoFlowOrderDetailService;
    private final OppoFlowTemplateService oppoFlowTemplateService;
    private final OppoFlowTemplateItemService oppoFlowTemplateItemService;
    private final OppoFlowTemplateDetailService oppoFlowTemplateDetailService;

    public OppoFlowOrderServiceImpl(OppoFlowOrderItemService oppoFlowOrderItemService, OppoFlowOrderDetailService oppoFlowOrderDetailService, OppoFlowTemplateService oppoFlowTemplateService, OppoFlowTemplateItemService oppoFlowTemplateItemService, OppoFlowTemplateDetailService oppoFlowTemplateDetailService) {
        this.oppoFlowOrderItemService = oppoFlowOrderItemService;
        this.oppoFlowOrderDetailService = oppoFlowOrderDetailService;
        this.oppoFlowTemplateService = oppoFlowTemplateService;
        this.oppoFlowTemplateItemService = oppoFlowTemplateItemService;
        this.oppoFlowTemplateDetailService = oppoFlowTemplateDetailService;
    }

    @Override
    public OppoFlowOrderDetailVO selectOrder(String id) {
        // 查询流程单据
        OppoFlowOrderDetailVO viewObject = getViewObject(id, OppoFlowOrderDetailVO.class);
        // 查询流程阶段
        QueryWrapper<OppoFlowOrderItemDetailVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", id);
        Pagination pagination = new Pagination().setPageIndex(1);
        pagination.setPageSize(100);
        List<OppoFlowOrderItemDetailVO> viewObjectList = oppoFlowOrderItemService.getViewObjectList(queryWrapper, pagination, OppoFlowOrderItemDetailVO.class);
        // 排序
        viewObjectList.sort(Comparator.comparing(OppoFlowOrderItemDetailVO::getSort));
        // 查询流程明细
        List<String> ids = BeanUtils.collectToList(viewObjectList, OppoFlowOrderItemListVO::getId);
        //QueryWrapper<OppoFlowOrderDetailDetailVO> qw = new QueryWrapper<>();
        //qw.in("item_id", ids);
        //List<OppoFlowOrderDetailDetailVO> details = oppoFlowOrderDetailService.getViewObjectList(qw, pagination, OppoFlowOrderDetailDetailVO.class);
        // set 值
        viewObject.setItems(viewObjectList);
        //Map<String, List<OppoFlowOrderDetailDetailVO>> groupByItem = details.stream().collect(Collectors.groupingBy(OppoFlowOrderDetail::getItemId));
        //for (OppoFlowOrderItemDetailVO item : viewObjectList) {
        //    List<OppoFlowOrderDetailDetailVO> ds = groupByItem.get(item.getId());
        //    item.setDetails(ds);
        //}
        return viewObject;
    }

    @Override
    public String createOrder(String tempId) {
        // 新建流程单
        OppoFlowTemplate template = oppoFlowTemplateService.getEntity(tempId);
        OppoFlowOrder oppoFlowOrder = new OppoFlowOrderListVO();
        oppoFlowOrder.setIsOver(false);
        oppoFlowOrder.setStatus("ready");
        // todo 单据号规则
        //oppoFlowOrder.setCode("");
        oppoFlowOrder.setTemplateId(tempId);
        createEntity(oppoFlowOrder);
        // 新建流程阶段
        List<OppoFlowTemplateItem> tempItems = oppoFlowTemplateItemService.getEntityList(QueryBuilder.toQueryWrapper(new OppoFlowTemplateItemDTO().setTemplateId(tempId)));
        if(tempItems.isEmpty()){
            throw new RuntimeException("流程模板没有流程阶段");
        }
        List<OppoFlowOrderItem> items = new ArrayList<>();
        for (OppoFlowTemplateItem tempItem : tempItems) {
            OppoFlowOrderItem item = new OppoFlowOrderItem();
            //item.setCode("");
            //item.setStatus("");
            item.setTemplateItemId(tempItem.getId());
            item.setSort(tempItem.getSort());
            item.setName(tempItem.getName());
            item.setIsBegin(tempItem.getIsBegin());
            item.setIsEnd(tempItem.getIsEnd());
            item.setIsCurrent(false);
            item.setOrderId(oppoFlowOrder.getId());
            item.setPrev(tempItem.getPrev());
            item.setFormId(tempItem.getFormId());
            items.add(item);
        }
        items.sort(Comparator.comparing(OppoFlowOrderItem::getSort));
        items.get(0).setIsCurrent(true);
        oppoFlowOrderItemService.createEntities(items);
        // 维护阶段流
        for (int i = 0; i < items.size(); i++) {
            OppoFlowOrderItem item = items.get(i);
            if (i < items.size() - 1) {
                item.setNext(items.get(i + 1).getId());
            }
            if (i > 0) {
                item.setPrev(items.get(i - 1).getId());
            }
        }
        oppoFlowOrderItemService.updateEntities(items);
        // 新建流程明细
        //Map<String, List<OppoFlowOrderItem>> groupByTid = items.stream().collect(Collectors.groupingBy(OppoFlowOrderItem::getTemplateItemId));
        //List<String> tids = BeanUtils.collectToList(tempItems, OppoFlowTemplateItem::getId);
        //QueryWrapper qw = new QueryWrapper();
        //qw.in("item_id", tids);
        //List<OppoFlowTemplateDetail> tds = oppoFlowTemplateDetailService.getEntityList(qw);
        //List<OppoFlowOrderDetail> orderDetails = new ArrayList<>();
        //for (OppoFlowTemplateDetail td : tds) {
        //    OppoFlowOrderItem oppoFlowOrderItem = groupByTid.get(td.getItemId()).get(0);
        //    OppoFlowOrderDetail detail = new OppoFlowOrderDetail();
        //    detail.setTemplateDetailId(td.getId());
        //    detail.setItemId(oppoFlowOrderItem.getId());
        //    detail.setContent(td.getContent());
        //    detail.setType(td.getType());
        //    //detail.setCode("");
        //    orderDetails.add(detail);
        //}
        //oppoFlowOrderDetailService.createEntities(orderDetails);
        return oppoFlowOrder.getId();
    }

    @Override
    public void commit(OppoFlowOrderDetailVO detailVO, String itemId) {
        if (detailVO.getIsOver()) {
            throw new RuntimeException("流程已结束不能再次提交！");
        }
        detailVO.setStatus("going");
        List<OppoFlowOrderItemDetailVO> items = detailVO.getItems();
        // 阶段排序
        items.sort(Comparator.comparing(OppoFlowOrderItemDetailVO::getSort));
        List<OppoFlowOrderDetailDetailVO> details = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            OppoFlowOrderItemDetailVO item = items.get(i);
            //List<OppoFlowOrderDetailDetailVO> detailList = item.getDetails();
            //if (detailList != null && !detailList.isEmpty()) {
            //    details.addAll(detailList);
            //}
            // 流程推进
            if (item.getIsCurrent() && i < items.size() - 1) {
                item.setIsCurrent(false);
                OppoFlowOrderItemDetailVO next = items.get(i + 1);
                next.setIsCurrent(true);
            }
            // 最后阶段 修改单据状态为结束
            if (item.getIsCurrent() && i == items.size() - 1) {
                item.setIsCurrent(false);
                detailVO.setStatus("over");
                detailVO.setIsOver(true);
            }
        }
        updateEntity(detailVO);
        oppoFlowOrderItemService.updateEntities(items);
        oppoFlowOrderDetailService.updateEntities(details);
    }
}